import java.io.File;
import java.io.StringReader;
import java.util.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class FeedParserX {
	Document doc;
	int cur = 0;
	boolean good;
	public FeedParserX(String html){
		// TEEME XML-ist (STRING) DOCUMENT
		html = compactTxt (html);
		DocumentBuilderFactory Factory=DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder Builder=Factory.newDocumentBuilder();
				InputSource Entries=new InputSource(new StringReader(html));
				doc = Builder.parse(Entries);
				doc.normalizeDocument();
				if (doc.getFirstChild().getNodeName().equals("rss")) {
					toXml("buf1.xml");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	Document getDoc() {
		return doc;
	}
	
	String compactTxt (String txt) {
		while (txt.indexOf("> ") > 0) {
			txt = txt.replace("> ", ">");
		}
		return txt;
	}
	@SuppressWarnings("unchecked")
	void sortDocByDates(boolean desc){
		NodeList items = doc.getElementsByTagName("item");
		Dates date = new Dates("");
		Node node = items.item(0).getParentNode();
		for (int i = 0; i < items.getLength(); i++){
			Node pubDate = items.item(i).getLastChild();
			date.Str2Cal(pubDate.getTextContent()+"C");
			Element item = (Element) pubDate.getParentNode();
			int vh = date.DateDiffNow();
			String vahe = String.valueOf(vh);
			if(vh<10) vahe = "00"+vahe;
			if (vh <100 && vh >9) vahe = "0" + vahe;
			item.setAttribute("vahe", vahe);
		}
		List<Node> nodes = new ArrayList<Node>();
		for (int i = 0; i < items.getLength(); i++) {
			Node tNode = items.item(i);
			nodes.add(tNode);
		}
		Comparator<Node> comp = new MyComparator();
		if (desc){
			Collections.sort(nodes, Collections.reverseOrder(comp));
		} else {
			Collections.sort(nodes, comp);
		}
		 for (Object nx : nodes) {
			 Element boo = (Element) nx;
			node.appendChild(boo);
		 }
		//toXml();
		
	}
	class MyComparator implements Comparator {

		@Override
		public int compare(Object arg0, Object arg1) {
			if (arg0 instanceof Element && arg1 instanceof Element) {
	            return ((Element) arg0).getAttribute("vahe").compareTo(
	                            ((Element) arg1).getAttribute("vahe"));
	    } else {
	            return ((Node) arg0).getNodeName().compareTo(
	                            ((Node) arg1).getNodeName());
	    }
			// TODO Auto-generated method stub
		}

	
}
	
	 void toXml (String fnm) {
			try {
				Transformer xmlMaker = TransformerFactory.newInstance().newTransformer();
				try {
					xmlMaker.transform(new DOMSource(doc), 
							new StreamResult(new File(fnm)));
				} catch (TransformerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (TransformerConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerFactoryConfigurationError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	 boolean transform (String lang) {
		 NodeList dates = doc.getElementsByTagName("date");
		 for (int i = dates.getLength()-1; i >= 0; i--) {
			 Element curDate = ((Element) dates.item(i));
			 NodeList langs =  curDate.getElementsByTagName("lang");
			 for (int j = langs.getLength()-1; j >= 0; j --) { // EEMALDAME TEISI KEELI
				 if (!langs.item(j).getAttributes().item(0).getTextContent().equals(lang)) {
					 curDate.removeChild(langs.item(j));
				 }
			 }
			if (langs.getLength() != 0) {
				NodeList langChilds = langs.item(0).getChildNodes();
				Element pubDate1 = doc.createElement("pubDate1");
				dates.item(i).appendChild(pubDate1);
				 for (int j = langChilds.getLength()-1; j >=0; j--) {
					 if (langChilds.item(j).getNodeName().equals("pubDate")) {
						 pubDate1.setTextContent(langChilds.item(j).getTextContent());
						 langChilds.item(j).setTextContent(curDate.getAttribute("value"));
					 }
					 curDate.appendChild(langChilds.item(j));				 
				 }
				 curDate.removeChild(langs.item(0));
				 curDate.appendChild(curDate.getElementsByTagName("pubDate").item(0));
			}
			doc.renameNode(curDate, null, "item");
		 }
		 toXml("new.xml");
		 return doc.getElementsByTagName("pubDate").getLength() == 0;
		 
		 
	 }
	 String [] toArr (Node curDate) {
		 String [] out = new String [6];
		 String [] tags = {"title", "pubDate1", "description", "pubDate", "pubDate", "link"};
		 Element parent = (Element) curDate.getParentNode();
		 for (int i = 0; i < 6; i++) {
			 out[i] = parent.getElementsByTagName(tags[i]).item(0).getTextContent();
		 }
		 out[3] = "b";
		 out[4] = "b";
		 return out;
	 }
}
